/**
 * Created by bieber on 2014/10/16.
 */
;(function(){
    
    //初始化核心类
    var ue;
    var context = this;

    //页面初始化的时候进行页面渲染
    $().ready(function() {
        new templateInclude(["templates/rootlogin.tmp","templates/templates.tmp","templates/request.tmp","templates/group.tmp","templates/scene.tmp","templates/batchrequest.tmp"]);
        initContext();
        createEntityTpl();
        bindAddKV();
        formatPage();
        checkLogin();
        rootLogin();
        $(".entities").css({"maxHeight":generateMenuHeight(),"overflow":"auto"});
        $(".groups").css({"maxHeight":generateMenuHeight(),"overflow":"auto"});
        $(".scene").css({"maxHeight":generateMenuHeight(),"overflow":"auto"});
        $(".nowYear").text(new Date().getFullYear());
    });
    function checkLogin(){
        var isRoot = context.smtPost.checkLogin();
        if(isRoot==true||isRoot=='true'){
            $("#loginLabel").text("已登录");
            $(".need-root-auth").show();
            return true;
        }else{
            $("#loginLabel").text("Root登录");
            $(".need-root-auth").hide();
            return false;
        }
    }
    context.rendingPageHandler=function(){
        checkLogin();
        $(".console-result-container .console-close").click();
    };
    function rootLogin(){
            $("#rootLogin").bind("click",function(){
                var isLogined = checkLogin();
                if(isLogined){
                    var editDialog = new dialog({
                        title:"确认",
                        content:"确认登出？",
                        isConfirm:true,
                        onOk:function(){
                            context.smtPost.permission(null,isLogined,function(status){
                                if(status){
                                    editDialog.close();
                                }else{
                                    var errorDialog = new dialog({
                                        content:"服务器发生异常！"
                                    });
                                    errorDialog.open();
                                }
                                checkLogin();
                            });
                         
                        }
                    });
                    editDialog.open();
                }else{
                    var editDialog = new dialog({
                        title:"登录",
                        content:template("rootLoginTpl",{}),
                        isConfirm:true,
                        onOk:function(){
                            var password = $("#loginWrapper input[name='password']").val();
                            if($.trim(password)==""){
                                var errorDialog = new dialog({
                                    content:"请输入密码"
                                });
                                errorDialog.open();
                                return ;
                            }
                            context.smtPost.permission(password,isLogined,function(status){
                                if(status){
                                    editDialog.close();
                                    checkLogin();
                                }else{
                                    var errorDialog = new dialog({
                                        content:"密码错误，登录失败！"
                                    });
                                    errorDialog.open();
                                }
                            });
                        }
                    });
                    editDialog.open();
                }
            });
    }
    function generateMenuHeight(){
        return $("#body").height()-45;
    }
    function initContext(){
        context.smtPost = new smartpost(initContext);
        context.entities = smtPost.entities;
        context.group = smtPost.group;
        context.scene = smtPost.scene;
        context.env = smtPost.env;
        rendingEnvSelector();
        $(".tabs").tabs({
            beforeActivate : function(event, ui) {
                ui.oldTab.removeClass("active");
                ui.newTab.addClass("active");
            }
        });

        //append entity
        var html = loadEntities(entities,true);
        $(".entities ul").html(html);
        context.rendingPageHandler();
        bindEntityEdit();
        html = '';
        //append group
        for ( var pro in group) {
            var item = group[pro];
            html += template("groupEntityTpl",item);
        }
        $(".groups .list-group").html(html);
        context.rendingPageHandler();
        html = '';
        //append scene
        for ( var pro in scene) {
            var item = scene[pro];
            html += template("sceneEntityTpl",item);
        }
        $(".scene ul").html(html);
        context.rendingPageHandler();
        bindEvent();
        $(".add-trigger").bind("click",function(){
            var type = $(this).attr("editor-type");
            switch (type){
                case 'group' : {
                    createEditGroupView({});
                    break;
                };
                case 'entity' : {
                    createEntityTpl();
                    bindAddKV();
                    break;
                };
                case 'scene' : {
                    initScene();
                    break;
                }
            }
        });
    }
    function createEditGroupView(data){
        $("#edit-contain").html(template("addGroupHead",{groupContent:template("addGroup",data)}));
        context.rendingPageHandler();
        bindAddGroup();
    }

    //格式化页面大小
    function formatPage(){
        var header=$("#header");
        var footer = $("#footer");
        var body =$("#body");
        var maxHeight=parseInt(document.documentElement.clientHeight)-parseInt(footer.height())-parseInt(body.offset().top)-5;
        body.css({height:maxHeight})
        $(".operation-domain").css({height:maxHeight,overflow:'auto'})
    }

    //当页面大小发生变化时候进行重新变化页面大小
    window.onresize=function(){
        formatPage();
    }

    function bindBatchInvoke(){
        $("#batchInvoke").bind("click",function(){
            var valid = new validator({validateTarget:$("#addEntityContainer")});
            var result = valid.validate();
            if(!result.result){
                var d=new dialog({
                    content:result.tip
                });
                d.open();
            }else{
                var entityJson = loadEntityData();
                filterParams(entityJson);
                var invokeTime=$("#addEntityContainer input[name='invokeTime']").val();
                var intervalTime=$("#addEntityContainer input[name='intervalTime']").val();
                if(!intervalTime||!invokeTime){
                    var errorDialog = new dialog({
                       content:"请输入调用次数以及每次执行间隔时间！"
                    });
                    errorDialog.open();
                    return ;
                }
                try{
                   intervalTime = parseInt(intervalTime);
                   invokeTime = parseInt(invokeTime);
                }catch(e){
                    var errorDialog = new dialog({
                        content:"调用次数以及每次执行间隔时间必须都是正整数！"
                    });
                    errorDialog.open();
                    return ;
                }
                if(invokeTime<=0){
                    var errorDialog = new dialog({
                        content:"调用次数必须大于零！"
                    });
                    errorDialog.open();
                    return ;
                }


                entityJson.invokeTime=invokeTime;
                entityJson.intervalTime=intervalTime;
                entityJson=copyObject(entityJson);
                entityJson.entityId=Math.uuid();
                var entities=[];
                entities.push(entityJson);

                batchInvokeConsoleStyleInit();
                smtPost.batchInvoke(entities,function(data){
                    batchInvokeConsoleStyleCallback(data);
                });

            }
        });
    }
    context.createBatchInvokeResultView=function(entities){
        var items="";
        for(var j=0;j<entities.length;j++){
            var entityJson = entities[j];
            var invokeTime = entityJson.invokeTime;
            for(var i=0;i<invokeTime;i++){
                var item={};
                item.title=entityJson.name+"#"+(i+1);
                item.index=entityJson.entityId+"-"+(i+1);
                items+=template("batchRequestEntityTpl",item);
            }
        }
        //$("#batchInvokeResultWindow").html(items);

        var batchInvokeDialog = new dialog({
            title:"调用结果",
            content:template("batchRequestTpl",{content:items}),
            isConfirm:true,
            onOk:function(){
                batchInvokeDialog.close();
            }
        });
        batchInvokeDialog.open();
        $("#batchInvokeResultWindow a:first").click();
        return batchInvokeDialog;
    }
    context.batchInvokeConsoleStyleCallback=function(data){
        $("#console-result-content-wrapper .waiting").remove();
        data.name=data.name+"#"+data.index;
        var resultHtml=template("consoleStyleResultTpl",data);
        $("#console-result-content-wrapper").append(resultHtml);
        var container = $(".operation-domain");
        container.animate({
             scrollTop :container.get(0).scrollHeight
         }, 'slow', 'linear');
        $(".console-result-container .console-request-tool").unbind("click");
        $(".console-result-container .console-request-tool").bind("click",function(){
            var me = $(this);
            var row=me.parents(".row:first");
            var responseContent = row.next();
            var className = me.attr("data");
            var currentActive=row.find(" .active");
            currentActive.removeClass("active");
            me.addClass("active");
            var currentActiveClassName = currentActive.attr("data");
            responseContent.find("."+currentActiveClassName).fadeOut();
            responseContent.find("."+className).fadeIn();
            if(className==="preview"){
                var textArea = responseContent.find("."+className).find("textarea");
                var contentType=textArea.attr("type");
                var inited=textArea.attr("inited");
                if(inited==="1"){
                    return;
                }
                if(contentType.indexOf("html")>=0){
                    var codeMirror = CodeMirror.fromTextArea(textArea.get(0), {
                        lineNumbers: true,
                        matchBrackets: true,
                        autofocus:true,
                        styleActiveLine: true,
                        lineWrapping: true,
                        foldGutter: true,
                        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
                        mode:"text/html"
                    });
                }else if(contentType.indexOf("xml")>=0){
                    var codeMirror = CodeMirror.fromTextArea(textArea.get(0), {
                        lineNumbers: true,
                        matchBrackets: true,
                        autofocus:true,
                        styleActiveLine: true,
                        lineWrapping: true,
                        foldGutter: true,
                        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
                        mode:"text/xml"
                    });
                }else if(contentType.indexOf("json")>=0){
                    Process(textArea.parent().get(0),textArea.val());
                }else{
                    var codeMirror = CodeMirror.fromTextArea(textArea.get(0), {
                        lineNumbers: true,
                        matchBrackets: true,
                        autofocus:true,
                        styleActiveLine: true,
                        lineWrapping: true,
                        foldGutter: true,
                        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
                        mode:"text/plain"
                    });
                }
                textArea.attr("inited","1");
            }
        });
        $("#console-result-content-wrapper .nav-tabs").each(function(){
            try{
                $(this).find(".console-request-tool:first").click();
            }catch(e){

            }
           
        });

    }

    context.batchInvokeConsoleStyleInit=function(){
        $("#console-result-content-wrapper").html('<span class="waiting" style="font-size: 13px;text-align: center;display: block;">正在请求.....</span>');
        $(".console-result-container").fadeIn();
        $(".console-result-container .result-wrapper").fadeIn();
        $(".console-result-container .console-close").unbind("click");
        $(".console-result-container .console-close").bind("click",function(){
            $(".console-result-container").fadeOut();
        });
    }
    context.batchInvokeCallback=function(data,batchInvokeDialog){
        var identify = data.entityId+"-"+data.index;
        var dataAttr = data.entityId+"-"+data.index;
        data.index=identify;
        $("#batchInvokeResultWindow .panel[data="+dataAttr+"]").find(".panel-body").html(template("requestResultTpl",data));
        $("#batchInvokeResultWindow .panel[data="+dataAttr+"]").find(".panel-body").find("textarea").each(function(){
            var item = $(this);
            var type = item.attr("type");
            if(type=="application/json"){
                Process(item.parent().get(0),item.val());
            }else{
                try{
                    var codeMirror = CodeMirror.fromTextArea(this, {
                        lineNumbers: true,
                        matchBrackets: true,
                        autofocus:true,
                        styleActiveLine: true,
                        lineWrapping: true,
                        foldGutter: true,
                        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
                        mode:type
                    });
                   // codeMirror.refresh();
                }catch(e){

                }
            }
        });
        if($("#batchInvokeResultWindow .panel").length>1){
            $("#batchInvokeResultWindow .panel[data="+dataAttr+"]").find("a:first").click();
        }
        var responseCode = $("#batchInvokeResultWindow .panel[data="+dataAttr+"]").find(".responseCode");
        var expendTime = $("#batchInvokeResultWindow .panel[data="+dataAttr+"]").find(".expendTime");
        expendTime.html(data.expendTime+"ms");
        if(data.responseCode!='200'){
            responseCode.addClass("label-warning")
        }else{
            responseCode.addClass("label-success")
        }
        responseCode.html(data.responseCode);
        batchInvokeDialog.rePosition();

    };

    //绑定保存请求实体的事件
    var bindSumbitEntity=function(){
        $("#addEntityContainer #saveEntityButton").bind("click",function(){

            var valid = new validator({validateTarget:$("#addEntityContainer")});
            var result = valid.validate();
            if(!result.result){
                var d=new dialog({
                    content:result.tip
                });
                d.open();
            }else{
                var entityJson = loadEntityData();
                $("#addEntityContainer input[name='entityId']").val(entityJson.entityId);
                smtPost.saveRequestEntity(entityJson);
                console.log(entityJson);
            }
        });

        $("#invokeEntity").bind("click",function(){
            var valid = new validator({validateTarget:$("#addEntityContainer")});
            var result = valid.validate();
            if(!result.result){
                var d=new dialog({
                    content:result.tip
                });
                d.open();
            }else{
                $("#addEntityContainer .panel-heading a").click();
                batchInvokeConsoleStyleInit();
                var entityJson = loadEntityData();
                filterParams(entityJson);
                entityJson.invokeTime=1;
                entityJson.intervalTime=0;
                smtPost.batchInvoke([entityJson],function(data){
                    batchInvokeConsoleStyleCallback(data);
                });
            }
        });
    }





    function bindAddGroup(){
        $("#saveGoupButton").bind("click",function(){
            submitGroupForm();
        });
    }

    function submitGroupForm(callback){
        var valid = new validator({validateTarget:$("#groupForm")});
        var result = valid.validate();
        if(!result.result){
            var errorDialog = new dialog({
                content:result.tip
            });
            errorDialog.open();
            return ;
        }
        var result = valid.validate();
        var group={};
        $("#groupForm").find("input").each(function(){
            var me = $(this);
            group[me.attr("name")]=me.val();
        });
        if(!group.groupId){
            group.groupId=Math.uuid();
        }
        $("#groupForm input[name='groupId']").val(group.groupId);
        smtPost.saveGroup(group,callback);
        return group;
    }


    //将页面请求实体拼装成JSON对象
    function loadEntityData(){
    	var entity={};
    	$("#addEntityContainer").find("input[data='raw']").each(function(){
    		var input= $(this);
    		entity[input.attr("name")]=input.val();
    	});
        $("#addEntityContainer").find("textarea[data='raw']").each(function(){
            var input= $(this);
            entity[input.attr("name")]=input.val();
        });

    	$("#addEntityContainer").find("[data='pair']").each(function(){
    		var row = $(this);
    		var parents = row.parents('[scope]');
    		var scope = parents.attr("scope");
    		var scopeObj=entity[scope];
    		if(!scopeObj){
    			scopeObj=[];
    			entity[scope]=scopeObj;
    		}
    		var inputs = row.find("input");
    		var pair={};
    		if(inputs.length==2){
    			var key = row.find("input[name='key']");
    			var value = row.find("input[name='value']");
    			pair[key.val()]=value.val();
    		}
    		scopeObj.push(pair);
    	});
        var envId = $("#envSelector input:first").val();
        entity.envId=envId;
        if(ue){
            var value = ue.getValue();
            if(value&&$.trim(value)){
                entity.params=value;
            }
        }
        if(!entity.entityId){
            entity.entityId=Math.uuid();
        }
    	return entity;
    }
    function toggleEntityEditContainer(){
        $("#addEntityContainer .panel-heading a").unbind();
        $("#addEntityContainer .panel-heading a").bind("click",function(){
            $("#addEntityContainer .panel-body").slideToggle();
        });
    }
    //绑定当点击某个请求实体的名称时候，进行对这个实体进行编辑
    function bindEntityEdit(){
        $(".entityAction").unbind("click");
        $(".deleteEntity").unbind("click");
        $(".entityAction").bind("click",function(){
            var me = $(this);
            var entityId = me.parents(".list-group-item:first").attr("data");
            var entity = smtPost.getRequestEntity(entityId);
            var html=template("addRequestEntity",entity);
            $("#edit-contain").html(html);
            toggleEntityEditContainer();
            context.rendingPageHandler();
            if($("#requestParameters").length>0) {
                createRequestBodyEditor($("#requestParameters"));
            }
            bindEntityEditElement();
            bindAddKV();
            formatPage();
        });
        $(".deleteEntity").bind("click",function(){
            var me = $(this);
            var entityId = me.parents(".list-group-item:first").attr("data");
            var confirm = new dialog({title:"确认",isConfirm:true,content:"确认删除该请求实体吗？",onOk:function(){
                confirm.close();
                smtPost.deleteRequestEntity(entityId,function(data){
                    if(data.status){
                        var d=new dialog({
                            content:"删除数据成功！"
                        });
                        d.open();
                    }else{
                        var d=new dialog({
                            content:"删除数据失败！"
                        });
                        d.open();
                    }
                });
            },onCancel:function(){
                confirm.close();
            }});
            confirm.open();
        });
    }

    //将创建请求实体的视图渲染出来
    function createEntityTpl(){
        $("#edit-contain").html(template("addRequestEntity"),{});
        if($("#requestParameters").length>0) {
            createRequestBodyEditor($("#requestParameters"));
        }
        context.rendingPageHandler();
        bindEntityEditElement();
    }
    function createRequestBodyEditor(targetObj,isChangeMode){
       var value = "";
       if(ue){
           value = ue.doc.getValue();
           ue=undefined;
           $(".CodeMirror").remove();
       }
       var type  =  targetObj.attr("type");
       var mode="";
       switch(type){
           case "text":{
               mode="text/plain";
               break;
           }
           case "xml":{
               mode="text/xml";
               break;
           }
           case "json":{
               mode="application/json";
               break;
           }
       }
       ue= CodeMirror.fromTextArea(targetObj.get(0), {
            lineNumbers: true,
            matchBrackets: true,
            lineWrapping: true,
            foldGutter: true,
            gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
            autofocus:true,
            mode:mode
       });
       ue.setOption("theme", "eclipse");
       if(value&& $.trim(value)!=''&&isChangeMode){
            ue.setValue(value);
            ue.refresh();
       }
    }

    function createNotFormRequestBody(data,type,isChangeMode){
        if($("#requestParameters").length<=0){
            data.type=type;
            $("#parameters").html(template("plainTextTpl",data));
        }else{
            $("#requestParameters").attr("type",type);
        }
        context.rendingPageHandler();
        createRequestBodyEditor($("#requestParameters"),isChangeMode);
    }
    //绑定编辑请求实体视图上面事件
    function bindEntityEditElement(){
        var parameterTypeSelect = new selector({selector: $("#request-parameters"),onChange:function(event){
            var href=event.selectedHref;
            //$("#request-parameters").prev().val(event.value);
            switch (href){
                case '#text' :{
                    createNotFormRequestBody({},"text",true);
                    break;
                }
                case '#json' :{
                    createNotFormRequestBody({},"json",true);
                    break;
                }
                case '#xml' :{
                    createNotFormRequestBody({},"xml",true);
                    break;
                }
                case '#html' :{
                    createNotFormRequestBody({},"html",true);
                    break;
                }
                case '#form' :{
                    if(ue){
                        ue=undefined;
                    }
                    $("#parameters").html(template("keyValueTpl",{}));
                    bindAddKV();
                    break;
                }
            }
            return true;
        }});
        var requestTypeSelector = new selector({selector:$("#requestType")});
        getGroups();
        bindSumbitEntity();
        bindBatchInvoke();
    }



    //获取分组信息
    function getGroups(){
    	var itemsHtml='';
        var groupSelector=$("#groupSelector");
        var selectedVal = groupSelector.find("input:first").val();
        var selectedGroupName;
    	for(var i in group){
            if(group[i].groupId==selectedVal){
                selectedGroupName=group[i].name;
            }
    		itemsHtml+=template("groupItemTpl",group[i]);
    	}
        if(selectedGroupName){
            groupSelector.find("b").text(selectedGroupName);
        }
        groupSelector.find(".divider").after(itemsHtml);
    	//groupSelector.find(".divider").append(itemsHtml);
    	 var groupSelect = new selector({selector:groupSelector,onChange:function(event){
             var selectedHref = event.selectedHref;
             if(selectedHref=='#addGroupOption'){
                 var addGroupHtml = template("addGroup",{});
                 var addGroupDialog = new dialog({
                    title:"添加分组",
                    content:addGroupHtml,
                    isConfirm:true,
                    onOk:function(){
                       var tempGroup =  submitGroupForm(function(data){
                           if(!data.status){
                               var failDialog = new dialog({
                                   title:"提示",
                                   content:data.error
                               })
                               failDialog.open();
                               initContext();
                           }else{
                               addGroupDialog.close();
                               var successDialog = new dialog({
                                   title:"提示",
                                   content:"添加分组成功"
                               })
                               successDialog.open();
                               groupSelector.find(".divider").after(template("groupItemTpl",tempGroup));
                               groupSelect.rebindEvent();
                               initContext();
                           }
                       });

                    }
                 });
                 addGroupDialog.open();
                 return false;
             }
             return true;
         }});
    }

    //获取请求实体列表
    function loadEntities(entities,isEntity) {
        var html = "";
        for ( var pro in entities) {
            var item = entities[pro];
            item.isEntity=isEntity;
            html +=template("entityTpl",item);
        }
        return html;
    }

    //绑定Bar切换事件
    function bindEvent() {
        $(".groupBar").bind( "click",function() {
                var me = $(this);
                var hasSlideDown = false;
                if (me.find("i").hasClass("glyphicon-chevron-down")) {
                    hasSlideDown = true;
                }
                $(".groupBar .glyphicon-chevron-down:first").addClass(
                    "glyphicon-chevron-right");
                $(".groupBar .glyphicon-chevron-down:first").removeClass(
                    "glyphicon-chevron-down");
                $(".groupBar").next().slideUp();
                if (hasSlideDown) {
                    return;
                }
                me.find("i:first").addClass("glyphicon-chevron-down");
                var groupId = me.attr("data");
                var entities = smtPost.getGroupDetails(groupId);
                var html = loadEntities(entities,false);
                me.next().find("ul").html(html);
                context.rendingPageHandler();
                me.next().slideDown();
                bindEntityEdit();
            });
        $(".groupBar .editGroup").bind("click",function(){
            var me = $(this);
            var groupId = me.parents("li:first").attr("data");
            var groupItem = group[groupId];
            createEditGroupView(groupItem);
        });
        $(".groupBar .glyphicon-remove").bind("click",function(){
            var me = $(this);
            var groupId = me.parents("li:first").attr("data");
            var entitiesIngroup = smtPost.getGroupDetails(groupId);
            if(entitiesIngroup.length>0){
                var errorDialog = new dialog({
                    content:"该分组还包含请求实体，不能进行删除！"
                })
                errorDialog.open();
                return ;
            }
            var confirmDialog = new dialog({
               title:"确认",
               content:"确认删除该分组吗？",
               isConfirm:true,
               onOk:function(){
                   confirmDialog.close();
                   smtPost.deleteGroup(groupId);
               }
            });
            confirmDialog.open();
        });
        $(".sceneBar a").bind("click",function(){
            editScene($(this));
        });
        $(".sceneBar .glyphicon-remove").bind("click",function(){
            deleteScene($(this));
        });
        $(".sceneBar .glyphicon-file").bind("click",function(){
            copyScene($(this));
        });
        $(".sceneBar") .bind("click",
            function() {
                var me = $(this);
                var hasSlideDown = false;
                if (me.find("i").hasClass("glyphicon-chevron-down")) {
                    hasSlideDown = true;
                }
                $(".sceneBar .glyphicon-chevron-down:first").addClass(
                    "glyphicon-chevron-right");
                $(".sceneBar .glyphicon-chevron-down:first").removeClass(
                    "glyphicon-chevron-down");
                $(".sceneBar").next().slideUp();
                if (hasSlideDown) {
                    return;
                }
                me.find("i:first").addClass("glyphicon-chevron-down");
                var sceneId = me.attr("data");
                var scene = smtPost.getSceneDetails(sceneId);
                var entities = [];
                for ( var i = 0; i < scene.requestSequence.length; i++) {
                    entities
                        .push(smtPost
                            .getRequestEntity(scene.requestSequence[i].entityId));
                }
                var html = loadEntities(entities,false);
                me.next().find("ul").html(html);
                me.next().slideDown();
                context.rendingPageHandler();
                bindEntityEdit();
            });
    }

    function previewContent(viwer){
        debugger;
        viwer.document.body.innerHTML=content;
    }
})();
